<?php
class Mageex_AdvanceSeo_Controller_Router extends Mage_Core_Controller_Varien_Router_Abstract
{
	public function initControllerRouters($observer)
	{
		$front = $observer->getEvent()->getFront();
		$front->addRouter('advanceseo', $this);
	}
	public function match(Zend_Controller_Request_Http $request) 
	{
		if(!Mage::isInstalled()) {
            Mage::app()->getFrontController()->getResponse()
                ->setRedirect(Mage::getUrl('install'))
                ->sendResponse();
            exit;
        }
		
        // Path for search result
        $suffix = Mage::helper('advanceseo/config')->getPathSearch();	
        
		$identifier = trim($request->getPathInfo(), '/');
		
		$arrUrl = explode('/',	 $identifier);
		$pathInfo = pathinfo($_SERVER['PHP_SELF']);
		$tagName = str_replace('-', ' ', $pathInfo['filename']);
		
		//Router for rewrite Tags
		if($arrUrl[0] == Mage::helper('advanceseo/config')->getPathTag()){

			$tagModel = Mage::getModel('tag/tag');
			$tagModel -> loadByName($tagName);
			$tagId = $tagModel->getId();
			if(!empty($tagId)){
				$request->setModuleName('tag')
	        			->setControllerName('product')
	        			->setActionName('list')
	        			->setRequestUri('?tagId='.$tagId);
	        	return true;
			}
			
		}
		if($arrUrl[0] == $suffix){  
			if(in_array(Mage::helper('advanceseo/config')->getPathFilter(), $arrUrl)){
				//$requestUri = '?';
				$count = 0;
				for($i=0; $i<count($arrUrl); $i++){	
					if(preg_match('/\-/',$arrUrl[$i])){
						$arrElement = explode('-',$arrUrl[$i]);
					
						if($arrElement[0] == 'cat'){
							array_shift($arrElement);
							$cateName = Mage::helper('advanceseo/data')->getNameConverted($arrElement);
							$category = Mage::getResourceModel('catalog/category_collection')
								->addFieldToFilter('name', array('eq' => $cateName));
							foreach ($category as $_category) {
								//$requestUri .= 'cat=' . $_category->getId() . '&';
								$requestUri['cat'] = $_category->getId();
							}
						}else{
							$product 	= Mage::getModel('catalog/product');
							$attribute	= $arrElement[0];
							$source 	= $product->getResource()->getAttribute($attribute)->getSource();
							array_shift($arrElement);	
							$nameLabel 	= Mage::helper('advanceseo/data')->getNameConverted($arrElement);
							
							$optionId = Mage::getSingleton('catalog/config')->getSourceOptionId($source, $nameLabel);
							if(empty($optionId)) {
								$optionId = $nameLabel;
							}
							if($count==0){
								//$requestUri .= $attribute . '=' . $optionId.'&';
								
							}else{	
								//$requestUri .= '&' . $attribute . '=' . $optionId;	
							}
							$requestUri[$attribute] = $optionId;
							$count++;
						}
					}
				}
				
				//$requestUri .= 'q=' . $arrUrl[1];
				$requestUri['q'] = $arrUrl[1];
				$request->setModuleName('catalogsearch')
							->setControllerName('result')
							->setActionName('index')
							->setParams($requestUri);
				return true;
				
			}else{
				$pos = strrpos($identifier, $suffix. '/');
				if ($pos !== false) {
					$suffix = Mage::helper('advanceseo/config')->getPathSearch();
					$url = str_replace($suffix.'/', '', $identifier);
					$char = Mage::getStoreConfig('catalog/seo/title_separator', Mage::app()->getStore()->getId());
					$param = preg_replace('/\\' . $char . '/', '+', $url);
					$param = str_replace(Mage::helper('advanceseo/data')->getSuffix(), '', $param);
					
					$request->setModuleName('catalogsearch')
							->setControllerName('result')
							->setActionName('index')
							->setRequestUri('?q='.$param);
					return true;
				}
			}
		}
		//For Rewrite rss
		
			if($arrUrl[0] == 'rss'){
				$currentStoreId 		= Mage::app()->getStore()->getId();  
				$actionName				= '';
				$param					= '';
				if($arrUrl[1] == 'catalog'){
					//http://127.0.0.1/advanceseo/index.php/rss/catalog/index/cid/13/store_id/1/
	
					$categoryName = str_replace(Mage::getStoreConfig('catalog/seo/category_url_suffix', Mage::app()->getStore()->getId()), '', $arrUrl[2]);
	
				 	$category = Mage::getModel('catalog/category')->getCollection();
					//$category->addFieldToFilter('name', $categoryName);
					$category->addAttributeToFilter('name', $categoryName);
					foreach($category as $cat)
					{
						$catId = $cat->getId();
					}
					
					$actionName = 'category';
					$param 		= '/cid/'. $catId .'/store_id/'.$currentStoreId.'/';
					//exit();
					if(Mage::helper('advanceseo/config')->isEnableRewriteRss()){
						$request->setPathInfo('/rss/catalog/index'.$param);
					}
					
				}else{
					$actionName = $arrUrl[1];
					//http://127.0.0.1/advanceseo/index.php/rss/new/index/store_id/1/
					$currentGroupCategoryId = Mage::getSingleton('customer/session')->getCustomerGroupId();
					if($arrUrl[1] == 'new'){
						$param = '/store_id/'.$currentStoreId.'/';
						
					}else{
						$param = '/store_id/'.$currentStoreId.'/cid/'.$currentGroupCategoryId.'/';
					}
				}
				
				$request->setModuleName('rss')
		        			->setControllerName('catalog')
		        			->setActionName($actionName)
		        			->setRequestUri($param);
		      	
		        return true;
			}
			//Router url filter search
			
			$key = array_keys($arrUrl, Mage::helper('advanceseo/config')->getPathFilter());
			
			if(in_array(Mage::helper('advanceseo/config')->getPathFilter(), $arrUrl) && $key[0]>0){
				
				$identifier = trim($identifier, Mage::helper('advanceseo/data')->getSuffix());
				$arrUrl		= explode('/',	 $identifier);
				$requestUri = '?';
				//array_shift($arrUrl);
				$count = 0;
				for($i=0; $i<count($arrUrl); $i++){	
					if(preg_match('/\-/',$arrUrl[$i]) && $i>$key[0]){
						$arrElement = explode('-',$arrUrl[$i]);	
						if($arrElement[0] == 'cat'){
							array_shift($arrElement);	
							$cateName = Mage::helper('advanceseo/data')->getNameConverted($arrElement);
							$category = Mage::getResourceModel('catalog/category_collection')
								->addFieldToFilter('name', array('eq' => $cateName));
							foreach ($category as $_category) {
								$requestUri .= 'cat=' . $_category->getId() . '&';
							}
						}else{
							$product 	= Mage::getModel('catalog/product');
							$attribute	= $arrElement[0];
							$source 	= $product->getResource()->getAttribute($attribute)->getSource();
							array_shift($arrElement);	
							$nameLabel 	= Mage::helper('advanceseo/data')->getNameConverted($arrElement);
							
							$optionId = Mage::getSingleton('catalog/config')->getSourceOptionId($source, $nameLabel);
							if(empty($optionId)) {
								$optionId = $nameLabel;
							}
							if($count==0){
								$requestUri .= $attribute . '=' . $optionId;
							}else{	
								$requestUri .= '&' . $attribute . '=' . $optionId;	
							}
							$count++;
						}
					}
				}
				
				//echo $requestUri;
				//exit;
				/*$request->setModuleName('advanceseo')
						->setControllerName('index')
						->setActionName('index')
						->setRequestUri($requestUri);
				*/
				$arrElemnt = explode('-',$arrUrl[$key[0]-1]);
				$cateName = Mage::helper('advanceseo/data')->getNameConverted($arrElemnt);
				$category = Mage::getResourceModel('catalog/category_collection')
								->addFieldToFilter('name', array('eq' => $cateName));
				foreach ($category as $_category) {
					$currentCategoryId =  $_category->getId();
				}
				
				$request->setModuleName('catalog') 
						->setControllerName('category') 
						->setActionName('view') 
						->setParam('id' , $currentCategoryId)
						->setRequestUri($requestUri);
				//echo $requestUri;
				return true;
			}
		
		
		//End router for rewrite rss
        return false;
	}

	
}